var oUser = $('#sample_editable_user').dataTable({
    "bProcessing": true,
    "aLengthMenu": [
        [5, 15, 20, -1],
        [5, 15, 20, "All"] // change per page values here
    ],
    // set the initial value
    "aaSorting": [[0, "desc"]],
    "iDisplayLength": 5,
    "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
    "sPaginationType": "bootstrap",
    "oLanguage": {
        "sProcessing": "正在获取数据，请稍后...",
        "sLengthMenu": "每页显示_MENU_条记录",
        "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
        "oPaginate": {
            "sPrevious": "前一页",
            "sNext": "后一页",
        },
        "sZeroRecords": "抱歉， 没有找到",
        "sInfoEmpty": "没有数据"
    },

    "aoColumnDefs": [{
        'bSortable': false,
        'aTargets': [0]
    }
    ]
});
var UserEdit = function () {

    return {

        //main function to initiate the module
        init: function () {

            function restoreRow(oUser, nRow) {
                var aData = oUser.fnGetData(nRow);
                var jqTds = $('>td', nRow);

                for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
                    oUser.fnUpdate(aData[i], nRow, i, false);
                }
                oUser.fnUpdate('<a class="edit" href="">编辑</a>', nRow, 6, false);
                oUser.fnUpdate('<a class="delete" href="">删除</a>', nRow, 7, false);

                oUser.fnDraw();
            }

            function editRow(oUser, nRow) {
                var aData = oUser.fnGetData(nRow);
                var jqTds = $('>td', nRow);

                jqTds[1].innerHTML = '<input type="text" class="m-wrap small" value="' + aData[1] + '">'; //name
                jqTds[2].innerHTML = '<input type="text" class="m-wrap small" value="' + aData[2] + '">'; //ip
                jqTds[3].innerHTML = '<input type="text" class="m-wrap small" value="' + aData[3] + '">'; //passwd
                jqTds[4].innerHTML = '<input type="text" class="m-wrap small" value="' + aData[4] + '">'; //access
                jqTds[5].innerHTML = '<input type="text" class="m-wrap small" value="' + aData[5] + '">'; //other
                jqTds[6].innerHTML = '<a class="edit" href="">保存</a>';
                jqTds[7].innerHTML = '<a class="cancel" href="">取消</a>';
            }

            function GetNewUserIndex(oUser) {
                var nUser = oUser.fnGetNodes();
                var userMax = 0;
                for (var i = 0; i < nUser.length; i++) {
                    var tUser = oUser.fnGetData(nUser[i])
                    if (tUser[0] > userMax) {
                        userMax = tUser[0];
                    }

                }
                return parseInt(userMax) + 1;
            }

            function saveRow(oUser, nRow) {
                var jqInputs = $('input', nRow);
                var bsucc = checkDataEmpty(jqInputs);
                if (bsucc) {
                    oUser.fnUpdate(jqInputs[0].value, nRow, 1, false);
                    oUser.fnUpdate(jqInputs[1].value, nRow, 2, false);
                    oUser.fnUpdate(jqInputs[2].value, nRow, 3, false);
                    oUser.fnUpdate(jqInputs[3].value, nRow, 4, false);
                    oUser.fnUpdate(jqInputs[4].value, nRow, 5, false);
                    oUser.fnUpdate('<a class="edit" href="">编辑</a>', nRow, 6, false);
                    oUser.fnUpdate('<a class="delete" href="">删除</a>', nRow, 7, false);
                    oUser.fnDraw();
                }

                return bsucc;

            }

            function cancelEditRow(oUser, nRow) {
                var jqInputs = $('input', nRow);
                oUser.fnUpdate(jqInputs[0].value, nRow, 1, false);
                oUser.fnUpdate(jqInputs[1].value, nRow, 2, false);
                oUser.fnUpdate(jqInputs[2].value, nRow, 3, false);
                oUser.fnUpdate(jqInputs[3].value, nRow, 4, false);
                oUser.fnUpdate(jqInputs[4].value, nRow, 5, false);
                oUser.fnUpdate('<a class="edit" href="">编辑</a>', nRow, 6, false);
                oUser.fnDraw();
            }

            jQuery('#sample_editable_user_wrapper .dataTables_filter input').addClass("m-wrap medium"); // modify table search input
            jQuery('#sample_editable_user_wrapper .dataTables_length select').addClass("m-wrap small"); // modify table per page dropdown
            jQuery('#sample_editable_user_wrapper .dataTables_length select').select2({
                showSearchInput: false //hide search box with special css class
            }); // initialzie select2 dropdown


            var nEditing = null;

            $('#sample_editable_user_new').click(function (e) {
                e.preventDefault();
                var newUserId = GetNewUserIndex(oUser);

                var aiNew = oUser.fnAddData([newUserId, '', '', '', '', '',
                    '<a class="edit" href="">编辑</a>', '<a class="cancel" data-mode="new" href="">取消</a>'
                ]);
                var nRow = oUser.fnGetNodes(aiNew[0]);
                editRow(oUser, nRow);
                nEditing = nRow;
            });

            $('#sample_editable_user a.delete').live('click', function (e) {
                e.preventDefault();

                if (confirm("确定删除此行 ?") == false) {
                    return;
                }

                var nRow = $(this).parents('tr')[0];

                //alert("Deleted! Do not forget to do some ajax to sync with backend :)");
                var DelUser = oUser.fnGetData(nRow);
                var cs2DelUserData = {
                    "name": DelUser[1],
                    "ip": DelUser[2],
                    "passwd": DelUser[3],
                    "access": DelUser[4],
                    "other": DelUser[5],
                };
                $.post("/c2sDelUser", cs2DelUserData)
                    .success(function () {
                        oUser.fnDeleteRow(nRow);
                        alert("删除数据库成功");
                    });
            });

            $('#sample_editable_user a.cancel').live('click', function (e) {
                e.preventDefault();

                var nRow = $(this).parents('tr')[0];
                var bEmpty = checkAllRowEmpty(nRow);

                if (($(this).attr("data-mode") == "new") || bEmpty) {
                    oUser.fnDeleteRow(nRow);
                } else {
                    restoreRow(oUser, nEditing);
                    nEditing = null;
                }
            });

            $('#sample_editable_user a.edit').live('click', function (e) {
                e.preventDefault();

                /* Get the row as a parent of the link that was clicked on */
                var nRow = $(this).parents('tr')[0];

                if (nEditing !== null && nEditing != nRow) {
                    /* Currently editing - but not this row - restore the old before continuing to edit mode */
                    restoreRow(oUser, nEditing);
                    editRow(oUser, nRow);
                    nEditing = nRow;
                } else if (nEditing == nRow && this.innerHTML == "保存") {
                    /* Editing this row and want to save it */
                    var bAuth = saveRow(oUser, nEditing);
                    if (bAuth) {
                        nEditing = null;
                        //alert("Updated! Do not forget to do some ajax to sync with backend :)");
                        var UserData = oUser.fnGetData(nRow);
                        var cs2UserData = {
                            "name": UserData[1],
                            "ip": UserData[2],
                            "passwd": UserData[3],
                            "access": UserData[4],
                            "other": UserData[5],
                        };

                        $.post("/c2sSaveUser", cs2UserData)
                            .success(function () {
                                alert("更新用户数据库成功)");
                            });
                    }

                } else {
                    /* No edit in progress - let's start one */
                    editRow(oUser, nRow);
                    nEditing = nRow;
                }
            });

            function check_NameRepeat(name) {
                var nTrs = oUser.fnGetNodes();
                for (var i = 0; i < nTrs.length; i++) {
                    var t = oUser.fnGetData(nTrs[i])
                    if ((t[1] == name) && (nEditing != nTrs[i])) {
                        alert("用户名，重复id：" + t[0]);
                        return false;
                    }

                }
                return true;
            }

            //检查是不是全部列都是空的行
            function checkAllRowEmpty(nRow) {
                var aData = oUser.fnGetData(nRow);
                if ((aData[1] == "") && (aData[2] == "") && (aData[3] == "") && (aData[4] == "") && (aData[5] == "")) {
                    return true
                }
                return false
            }

            function checkDataEmpty(jqInputs) {
                var name = jqInputs[0].value;
                var ip = jqInputs[1].value;
                var passwd = jqInputs[2].value;
                var access = jqInputs[3].value;

                if (name == "") {
                    alert("name不能为空");
                    return false;
                }


                if (passwd == "") {
                    alert("passwd不能为空");
                    return false;
                }

                if (access == "") {
                    alert("access不能为空");
                    return false;
                }

                var  bname = check_NameRepeat(jqInputs[0].value);
                var bIpSucc;
                if (ip != "")
                {
                    bIpSucc  = check_IP(jqInputs[1].value);
                }else{
                    bIpSucc = true;
                }

                var bAccess = check_access(access);

                if (bIpSucc && bname && bAccess) {
                    return true;
                }
                return false;
            }

        }

    };

}();

function getUserData() {
    //数据量不是特别大，直接全部读取吧
    $.getJSON("/admingetUser", function (data, status) {
        if (status == "success") {
            $.each(data, function (i, item) {
                var aiNew = oUser.fnAddData([i + 1, item.name, item.ip, item.passwd, item.access, item.other,
                    '<a class="edit" href="">编辑</a>', '<a class="cancel" data-mode="new" href="">删除</a>'
                ]);

                var nRow = oUser.fnGetNodes(aiNew[0]);
                oUser.fnUpdate(i + 1, nRow, 0, false)
                oUser.fnUpdate(item.name, nRow, 1, false);
                oUser.fnUpdate(item.ip, nRow, 2, false);
                oUser.fnUpdate(item.passwd, nRow, 3, false);
                oUser.fnUpdate(item.access, nRow, 4, false);
                oUser.fnUpdate(item.other, nRow, 5, false);
                oUser.fnUpdate('<a class="edit" href="">编辑</a>', nRow, 6, false);
                oUser.fnUpdate('<a class="delete" href="">删除</a>', nRow, 7, false);
            });
            oUser.fnDraw();
        }
    });
}

function check_IP(ip) {
    var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;//正则表达式
    if (re.test(ip)) {
        if (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256)
            return true;
    }
    alert("IP格式有误！");
    return false;
}


function check_access(access) {
    var bAccess = false;
    var acceseInt = parseInt(access);
   switch (acceseInt){
       case ACCESS_TYPE.ACCESS_ADMIN:
       case ACCESS_TYPE.ACCESS_SERVER:
       case ACCESS_TYPE.ACCESS_REPORT:
           bAccess = true;
           break;
       default:
           alert("权限必须为1-3");
        break;
   }
    return bAccess;
}



